# logic/history_window.py

import tkinter as tk
import os
import tkinter as tk
import os
from logic.history_data import history, clear_history

ICE_BLUE   = "#A6E3E9"
SNOW_WHITE = "#E8F9FD"
DARK_BLUE  = "#1B6B93"

def show_history(root, set_expression_callback):
    win = tk.Toplevel(root)
    win.title("计算历史")
    win.geometry("290x380")
    win.configure(bg=ICE_BLUE)
    win.attributes("-topmost", True)

    # 设置图标
    if os.path.exists("logo.ico"):
        win.iconbitmap("logo.ico")

    # 历史列表
    lb = tk.Listbox(win,
        font=("微软雅黑", 18),
        bg=ICE_BLUE,
        fg="white",
        selectbackground=DARK_BLUE,
        selectforeground="white"
    )
    lb.pack(side="top", fill="both", expand=True, padx=10, pady=(10, 5))

    sb = tk.Scrollbar(win, command=lb.yview)
    sb.pack(side="right", fill="y")
    lb.config(yscrollcommand=sb.set)

    # 加载历史内容
    for item in history:
        lb.insert(tk.END, item)

    # 清除按钮
    def on_clear():
        clear_history()
        lb.delete(0, tk.END)

    clear_btn = tk.Button(
        win, text="清除历史", font=("微软雅黑", 12),
        bg=SNOW_WHITE, fg=DARK_BLUE,
        command=on_clear
    )
    clear_btn.pack(side="bottom", fill="x", padx=10, pady=(5, 10))

    # 点击历史记录加载表达式
    def on_select(evt):
        sel = lb.curselection()
        if not sel:
            return
        expr_str = history[sel[0]].split('=')[0].strip()
        set_expression_callback(expr_str)
        lb.selection_clear(0, tk.END)  # 不关闭窗口，只清除选中状态

    lb.bind("<<ListboxSelect>>", on_select)
